package demo.publishcomsumer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/***
 * @title Publisher
 * @description: 生产者发布消息 路由键：hello-routingKey
 * @author baiji
 * @version 1.0.0
 * @create 2023/9/1 11:31
 **/
public class Publisher {

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");
        try {
            // 创建连接实体
            Connection connection = factory.newConnection();
            // 创建信道，用于连接exchange
            Channel channel = connection.createChannel();
            // 声明一个交换器
            String exchangeName = "hello-exchange";
            // 永久的交换器
            channel.exchangeDeclare(exchangeName, "direct", true);

            String routingKey = "hello-routingKey";
            byte[] messageBodyBytes = "hello world , I am er gou zi".getBytes(StandardCharsets.UTF_8);

            // 发布消息
            channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);
            System.out.println("MQ 消息发送完成");
            // 关闭连接
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
